import User.Duser;
import User.User;
import User.people;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(name = "Bind_dgut")
public class Bind_dgut extends HttpServlet {
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
    {
        do_Bind(req, resp);
    }
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
    {
        do_Bind(req, resp);
    }
    protected void do_Bind(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        people p = (people)request.getSession().getAttribute("LOGIN");
        User user = (User)request.getSession().getAttribute("SELF");
        EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("MyDSTest");
        EntityManager entityManager = entityManagerFactory.createEntityManager();
        EntityTransaction entityTransaction = entityManager.getTransaction();
        Duser duser = null;
        if(p != null && user != null) {
            duser = new Duser(p.getUsername(), p.getName(), user.getEmail(), user.getPasswd(), user.getImg());
            if (entityManager.find(Duser.class, duser.getId()) == null) //莞工表有的账号都是已经绑定的了
            {
                try {
                    entityTransaction.begin();
                    entityManager.persist(duser);
                    entityTransaction.commit();
                } catch (Exception e) {
                    System.out.println("莞工绑定用户信息写入失败！");
                }
                User user1 = entityManager.find(User.class, user.getEmail());
                user1.setDgutid(duser.getId());
                try {
                    entityTransaction.begin();
                    entityManager.merge(user1);
                    entityManager.flush();
                    entityTransaction.commit();
                } catch (Exception e) {
                    System.out.println("绑定莞工账号失败！");
                }
                entityManager.close();
                request.getSession().setAttribute("SELF", user1);
                request.getSession().setAttribute("DGUT", duser);
                response.sendRedirect("/user.jsp");
            }
            else
            {
                System.out.println("该账户已经被绑定了！");
                response.sendRedirect("/error.jsp");
            }
        }
        else
        {
            response.sendRedirect("/error.jsp");
        }
    }
}
